import React, { useEffect, useState } from 'react';
import { Modal, notification } from 'antd';
import _ from 'lodash';
import { CheckOutlined, RollbackOutlined } from '@ant-design/icons';
import { PageConfig } from '@/components/schema-form-render/meta';
import { useInitData } from './use-events';
import { useScemaRender, useGetValue, getValue } from './utils';

const ModalForm = ({
  editData,
  loading,
  title,
  visible,
  onCancel,
  onOk,
  modalMetasConfig,
  filedConfig,
  formConfigs,
  tableData,
  eventMap,
  rowKey,
}: any) => {
  // const [value, setValue] = useState<null | any>(null);
  const path = useGetValue();
  const {form, SchemaFormRender} = useScemaRender(filedConfig, formConfigs);
  useEffect(() => {
    if (editData) {
      // setValue(editData);
        form.setValues({
          ...editData,
        })
    }
    return () => {
      form?.reset();
    }
  }, [editData]);
  let metaConfig = (eventMap.transformMetasConfig && eventMap.transformMetasConfig(modalMetasConfig, tableData||[], editData)) || modalMetasConfig;
  let config:PageConfig = _.cloneDeep(metaConfig);
  // 二次包装config
  const meta = useInitData(config, null, 'NORMAL', false);
  return (
    <Modal
      title={title}
      visible={visible}
      width={900}
      destroyOnClose
      onCancel={() => {

        const values = form.getFormState(path).values;
        Object.keys(values).forEach((i)=>{
          form.setValuesIn(i, '');
        })

        form?.reset();
        onCancel();
      }}
      maskClosable={false}
      confirmLoading={loading}
      onOk={() => {
          //fix: 此处组件值针对于嵌套form
          const values = form.getFormState(path).values;
          form.validate().then((res:any)=>{
            let val = {};
            if(values.formLayout){
              val = getValue(values, path);
            }else {
              val = values;
            }
            onOk({...editData,...val}, () => {
              Object.keys(val).forEach((i)=>{
                form.setValuesIn(i, '');
              })
              form?.reset();
            });
          }).catch((err:any)=>{
            console.log('err', err);
            // notification.error(err[0]?.messages);
          })
      }}
      cancelButtonProps={{
        icon: <RollbackOutlined />,
      }}
      okButtonProps={{
        icon: <CheckOutlined />,
      }}
    >
      <SchemaFormRender schema={meta?.schema} pageConfig={meta?.pageConfig} />
    </Modal>
  );
};

export default ModalForm;
